const cloud = require('wx-server-sdk')
cloud.init()

/*
发送订阅消息

@param skey 云函数httpLogin中定义的密钥
@param openid 用户的openid
@param trafficId 对应交通工具信息的ID

templateId需要要先在 https://mp.weixin.qq.com/ 上申请, 注意参数的格式要一致
*/
exports.main = async (event, context) => {
  let openid = event.openid
  if(!openid){
    openid = cloud.getWXContext().OPENID
  }
  try {
    var req = JSON.parse(event.body)
    var verify = await cloud.callFunction({
      name: 'httpLogin',
      data: {
        skey: req.skey
      }
    })

    if(!verify.result || !verify.result.matched){
      return {"error": "wrong skey"}
    }

    const result = await cloud.openapi.subscribeMessage.send({
      touser: openid,
      page: '/pages/room/room?roomId='+req.trafficId,
      lang: 'zh_CN',
      data: {
        number01: {
          value: '339208499'
        },
        date01: {
          value: '2015年01月05日'
        },
        site01: {
          value: 'TIT创意园'
        },
        site02: {
          value: '广州市新港中路397号'
        }
      },
      templateId: 'TEMPLATE_ID',
      miniprogramState: 'developer'
    })
    console.log(result)
    return result
  } catch (err) {
    console.log(err)
    return err
  }
}